import { Button, Form, Input, SigninFilled, LockFilled, EmailOutlined, RealnameFilled, InputType, REG_MAILBOX } from 'esy-ui';
import { observer } from 'mobx-react-lite';
import { postLogin, postRegistry } from '@/services';
import { useUserInfoStore } from '@/mobx';
import { useNavigation } from '@/hooks';

const { Item } = Form;

const preIconcn = 'text-xl mr-2';

const psdItem = {
  name: 'password',
  type: 'password',
  placeholder: '请输入6~12密码',
  prefix: <LockFilled className={preIconcn} />,
};

const nameItem = {
  name: 'name',
  type: 'text',
  placeholder: '请输入4~12位账号',
  rules: [{ required: true, message: '账号不能为空' }],
  prefix: <SigninFilled className={preIconcn} />,
};

export const lrData = Object.freeze({
  lg: {
    t: '登录',
    arr: [nameItem, { ...psdItem, rules: [{ required: true, message: '密码不能为空' }] }],
  },
  rg: {
    t: '注册',
    arr: [
      nameItem,
      {
        ...psdItem,
        getRules: (values) => [
          {
            validator: (_, value) => {
              if (!value) {
                return new Error('密码不能为空');
              }
              if (values.repassword !== value) {
                return new Error('两次输入的密码不一致');
              }
              return Promise.resolve();
            },
          },
        ],
      },
      {
        name: 'repassword',
        type: 'password',
        placeholder: '请再次输入密码',
        getRules: (values) => [
          {
            validator: (_, value) => {
              if (!value) {
                return new Error('确认密码不能为空');
              }
              if (values.password !== value) {
                return new Error('两次输入的密码不一致');
              }
              return Promise.resolve();
            },
          },
        ],
        prefix: <LockFilled className={preIconcn} />,
      },
      {
        name: 'email',
        type: 'email',
        placeholder: '请输入邮箱地址',
        prefix: <EmailOutlined className={preIconcn} />,
        rules: [
          {
            validator: (_, value) => {
              if (value && !REG_MAILBOX.test(value)) {
                return new Error('请输入有效的邮箱地址');
              }
              return Promise.resolve();
            },
          },
        ],
      },
      {
        name: 'nickname',
        type: 'text',
        placeholder: '请输入4~12位昵称',
        prefix: <RealnameFilled className={preIconcn} />,
      },
    ],
  },
});

function Login({ type }: { type: string }) {
  const [form] = Form.useForm();
  const { changeUserInfo } = useUserInfoStore();
  const navigate = useNavigation();

  const onSubmit = () => {
    form
      .validate()
      .then((values) => {
        let api = postRegistry;
        if (type === 'lg') {
          api = postLogin;
        }
        api(values)
          .then((res: any) => {
            if (type === 'lg') {
              changeUserInfo(res.data);
            } else {
              changeUserInfo({ token: res.data, name: values.name });
            }
            navigate('/', { replace: true });
          })
          .catch(() => {});
      })
      .catch(() => {});
  };

  return (
    <Form className='mt-10' form={form}>
      {lrData[type].arr.map((it) => (
        <Item key={it.name} name={it.name} rules={it.getRules ? it.getRules(form.getFieldsValue()) : it.rules}>
          <Input type={it.type as InputType} prefix={it.prefix} placeholder={it.placeholder} />
        </Item>
      ))}
      <Button className='w-full justify-center mt-6' type='primary' onClick={onSubmit}>
        {lrData[type].t}
      </Button>
    </Form>
  );
}

export default observer(Login);
